// 获取菜品数据
const { dishes } = require('../../data/dishes');

Page({
  data: {
    dish: null,
    quantity: 1,
    showNutrition: false,
    showIngredients: false,
    showCookingMethod: false
  },
  
  onLoad: function (options) {
    const dishId = parseInt(options.id);
    const dish = dishes.find(d => d.id === dishId);
    
    if (dish) {
      this.setData({
        dish
      });
    } else {
      // 如果没找到菜品，返回上一页
      wx.showToast({
        title: '菜品不存在',
        icon: 'none',
        duration: 1500
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 增加数量
  increaseQuantity: function() {
    this.setData({
      quantity: this.data.quantity + 1
    });
  },
  
  // 减少数量
  decreaseQuantity: function() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
    }
  },
  
  // 切换营养信息显示
  toggleNutrition: function() {
    this.setData({
      showNutrition: !this.data.showNutrition
    });
  },
  
  // 切换食材信息显示
  toggleIngredients: function() {
    this.setData({
      showIngredients: !this.data.showIngredients
    });
  },
  
  // 切换做法信息显示
  toggleCookingMethod: function() {
    this.setData({
      showCookingMethod: !this.data.showCookingMethod
    });
  },
  
  // 添加到购物车
  addToCart: function() {
    const { dish, quantity } = this.data;
    
    if (!dish) return;
    
    // 获取购物车
    const app = getApp();
    const cart = app.globalData.cart || [];
    
    // 检查菜品是否已在购物车中
    const existingItem = cart.find(item => item.id === dish.id);
    
    if (existingItem) {
      // 如果已存在，增加数量
      existingItem.quantity += quantity;
    } else {
      // 如果不存在，添加到购物车
      cart.push({
        ...dish,
        quantity: quantity
      });
    }
    
    // 更新全局数据
    app.globalData.cart = cart;
    
    // 更新本地存储
    wx.setStorageSync('cart', cart);
    
    // 显示添加成功提示
    wx.showToast({
      title: `已添加${quantity}份到购物车`,
      icon: 'success',
      duration: 1500
    });
  },
  
  // 立即购买
  buyNow: function() {
    this.addToCart();
    
    // 跳转到购物车页面
    setTimeout(() => {
      wx.switchTab({
        url: '/src/pages/cart/cart'
      });
    }, 1000);
  },
  
  // 分享菜品
  onShareAppMessage: function() {
    const { dish } = this.data;
    return {
      title: `推荐美食：${dish.name}`,
      path: `/src/pages/dish-detail/dish-detail?id=${dish.id}`,
      imageUrl: dish.image
    };
  }
})
